package com.example.huainanlive.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import coil.load
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ScreenUtils
import com.demon.androidbasic.base.MyActivity
import com.example.huainanlive.R
import com.example.huainanlive.bean.AddMsgBean
import com.example.huainanlive.bean.AddZanBean
import com.example.huainanlive.bean.LiveIdBean
import com.example.huainanlive.databinding.ActivityLivePlayBinding
import com.google.android.material.tabs.TabLayout
import com.tencent.live2.V2TXLiveDef
import com.tencent.live2.V2TXLivePlayer
import com.tencent.live2.V2TXLivePlayerObserver
import com.tencent.live2.impl.V2TXLivePlayerImpl
import java.util.*
import kotlin.concurrent.timerTask


class LivePlayActivity : MyActivity<ActivityLivePlayBinding>() {

    private var mLiveId: Long = 0L
    private var recordId: Long = 0L
    private var liveState: String? = null
    private lateinit var huiGuLiveViewModel: HuiGuLiveViewModel
    private lateinit var homeRunViewModel: HomeRunViewModel
    private var url: String?= null

    //直播 weSocket
    private var mWsViewModel: WsViewModel? = null

    private var mLivePlayer: V2TXLivePlayer? = null
    private var isLivePlaying: Boolean = false
    private var videoHeight = 0
    private var videoWidth = 0
    private var zanNum = 0
    private var firstTime: Long = 0
    private var timer: Timer? = null
    private var mLiveCoverImg: String? = null

    /**
     * 是否使用沉浸式状态栏
     */
    override val isStatusBarEnabled: Boolean
        get() = false

    //页面跳转
    companion object {
        fun forward(
            activity: Activity,
            liveId: Long = 0L,
            recordId: Long = 0L,
            liveState: String?,
        ) {
            val intent = Intent(activity, LivePlayActivity::class.java)
            intent.putExtra("liveId", liveId)
            intent.putExtra("recordId", recordId)
            intent.putExtra("liveState", liveState)
            activity.startActivity(intent)
        }
    }

    override fun initBind() {
        binding = ActivityLivePlayBinding.inflate(inflater)
    }

    @SuppressLint("SetTextI18n")
    fun receiveSocketData() {

        //开始直播
        mWsViewModel?.startLive?.observe(this){
            mLivePlayer?.startLivePlay(url);
        }
        //暂停直播
        mWsViewModel?.stopLive?.observe(this){
            mLivePlayer?.pauseAudio()
            mLivePlayer?.pauseVideo()

        }
        //继续直播
        mWsViewModel?.playLive?.observe(this){
            mLivePlayer?.resumeAudio()
            mLivePlayer?.resumeVideo()

        }
        //结束直播
        mWsViewModel?.endLive?.observe(this){
            mLivePlayer?.stopPlay()
        }
        //改变直播间设置
        mWsViewModel?.changeSetting?.observe(this){
            if (it.t?.imgTextModel == 0){
                binding.ivImageTextModel.visibility = View.VISIBLE
            }else{
                binding.ivImageTextModel.visibility = View.GONE
            }

            if (it.t?.isAudience == 0){
                binding.tvPeopleOnline.visibility = View.VISIBLE
            }else{
                binding.tvPeopleOnline.visibility = View.GONE
            }
        }
        //赞数量
        mWsViewModel?.addZan?.observe(this){
            binding.tvZan.text = "点赞: ${it.t}"
        }
        //在线人数
        mWsViewModel?.peopleOnline?.observe(this){
            binding.tvPeopleOnline.text = "在线观众: ${it.t}"
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        intent?.let {
            mLiveId = it.getLongExtra("liveId", 0)
            recordId = it.getLongExtra("recordId", 0)
            liveState = it.getStringExtra("liveState")
        }

        homeRunViewModel = ViewModelProvider(
            this,
            HomeRunViewModelFactory()
        )[HomeRunViewModel::class.java]

        huiGuLiveViewModel = ViewModelProvider(
            this
        )[HuiGuLiveViewModel::class.java]

        mWsViewModel = ViewModelProvider(
            this,
            WsViewModel.WsViewModelModelFactory()
        )[WsViewModel::class.java]

        binding.videoView.layoutParams.height = ScreenUtils.getScreenWidth() / 16 * 9
        //创建 player 对象
        mLivePlayer = V2TXLivePlayerImpl(this).apply {
            //关键 player 对象与界面 view
            setRenderView(binding.videoView)
            // 设置填充模式
            setRenderFillMode(V2TXLiveDef.V2TXLiveFillMode.V2TXLiveFillModeFit)

//        val flvUrl = "rtmp://pull.weibu.vip/live/175339_c731e41d38860b68b94ccaeac071d192"
            startLivePlay("http://stream.0554news.com/hnds1/playlist.m3u8?_upt=cc441e8f1669371377")
            this.setObserver(object : V2TXLivePlayerObserver() {
                override fun onStatisticsUpdate(
                    player: V2TXLivePlayer?,
                    statistics: V2TXLiveDef.V2TXLivePlayerStatistics?
                ) {
                    super.onStatisticsUpdate(player, statistics)
                    statistics?.let {
                        //以比特率判断是否在播放
                        isLivePlaying = it.audioBitrate > 0 || it.videoBitrate > 0
                        videoHeight = it.height
                        videoWidth = it.width
                    }
                }
            })
        }
        //webSocket的URl链接
        mWsViewModel?.initWebSocket()

        //TODO mLiveId无数据 为1可以有数据
        //聊天的列表
        huiGuLiveViewModel.getComment(liveId = 1)
        //留言的列表
        huiGuLiveViewModel.getMessage(liveId = 1)
        huiGuLiveViewModel.getWord(liveId = 1)
        //进入直播间
        huiGuLiveViewModel.enterLive(LiveIdBean().apply {
            liveId = 1
        })

        when (liveState) {
            "直播预告" -> {
                binding.tvLiveState.visibility = View.GONE
                huiGuLiveViewModel.liveHouseDetail(mLiveId)
            }
            "直播回顾" -> {
                binding.tvLiveState.text = liveState
                huiGuLiveViewModel.liveHouseRecordDetail(recordId)
            }
            "正在直播" -> {
                binding.tvLiveState.text = liveState
            }
        }

        //回顾的详情页 TODO 没有标题 没有图文直播需要的img
        huiGuLiveViewModel.getLiveHouseRecordDetailBean.observe(this) {
            binding.liveTitle.text = "直播: ${it.liveTitle}"
            binding.ivImageTextModel.load(it.liveCoverImg)
            mLiveCoverImg = it.liveCoverImg
            binding.ivSendMsg.isClickable = it.vo?.isComment == 0
            if (it.vo?.isAudience == 0){
                binding.tvPeopleOnline.visibility = View.VISIBLE
            }else{
                binding.tvPeopleOnline.visibility = View.GONE
            }
            if (it.recordStreamHttp?.isNotEmpty() == true){
                mLivePlayer?.startLivePlay(it.recordStreamHttp)
            }else if(it.recordStreamm3u8?.isNotEmpty() == true){
                mLivePlayer?.startLivePlay(it.recordStreamm3u8)
            }else if (it.recordStreamPlay?.isNotEmpty() == true){
                mLivePlayer?.startLivePlay(it.recordStreamPlay)
            }

//            mLivePlayer?.startLivePlay(it.recordStreamHttp)
        }

        //预告与进行中的详情页
        huiGuLiveViewModel.getLiveHouseDetailBean.observe(this) {
            binding.liveTitle.text = "直播: ${it.liveTitle}"
            binding.ivImageTextModel.load(it.liveCoverImg)
            mLiveCoverImg = it.liveCoverImg
//            mLivePlayer?.startLivePlay(it.liveStreamHttp)
            binding.ivSendMsg.isClickable = it.detailVo?.isComment == 0
            if (it.detailVo?.isAudience == 0){
                binding.tvPeopleOnline.visibility = View.VISIBLE
            }else{
                binding.tvPeopleOnline.visibility = View.GONE
            }

            if (it.liveStreamHttp?.isNotEmpty() == true){
                mLivePlayer?.startLivePlay(it.liveStreamHttp)
            }else if(it.liveStreamm3u8?.isNotEmpty() == true){
                mLivePlayer?.startLivePlay(it.liveStreamHttp)
            }else if (it.liveStreamPlay?.isNotEmpty() == true){
                mLivePlayer?.startLivePlay(it.liveStreamHttp)
            }

        }

        //给EditText添加关键字
        huiGuLiveViewModel.getWorldBean.observe(this) {
            for (i in 0 until it.size) {
                val textView = TextView(this)
                textView.apply {
                    text = "Text ${it[i].wordText}"
                    setTextColor(Color.WHITE)
                    setPadding(12, 4, 12, 4)
                    background = resources.getDrawable(R.color.red, null)
                    val params = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    params.setMargins(10, 10, 10, 10)
                    layoutParams = params
                    setOnClickListener {
                        binding.etMsg.setText(binding.etMsg.text.toString() + textView.text.toString())
                    }
                    binding.llKeyWord.addView(this, params)
                }
            }
        }
        //websocket监听
        receiveSocketData()
        //返回上一页
        binding.btBack.setOnClickListener {
            finish()
        }

        //显示留言ui
        binding.ivSendMsg.setOnClickListener {
            binding.llSendMsg.visibility = View.VISIBLE
        }

        //点赞
        binding.ivSendZan.setOnClickListener {
            binding.periscopeLayout.addHeart()
            val secondTime= System.currentTimeMillis();
            if (secondTime-firstTime>2000){
                firstTime=System.currentTimeMillis();
            }else{
                zanNum++
            }
            timer?.cancel()


        }
        timer = Timer().also {
            it.schedule(timerTask {
                if (zanNum != 0){
                    huiGuLiveViewModel.addZan(AddZanBean().apply {
                        liveId
                        zanNum
                    })
                    zanNum = 0
                }
            }, 0, 5000) //改为5秒
        }

        //发送留言
        binding.tvSend.setOnClickListener {
            binding.llSendMsg.visibility = View.GONE
            val keywords = binding.etMsg.text.toString()
            if (keywords.isEmpty()) {
                binding.etMsg.requestFocus()
                return@setOnClickListener
            }
            KeyboardUtils.hideSoftInput(binding.etMsg)
            //添加留言
            huiGuLiveViewModel.addMsg(AddMsgBean().apply {
                liveId = 1
                userMsg = binding.etMsg.text.toString()
            })
            binding.etMsg.text.clear()
            binding.etMsg.clearFocus()
        }


        //里面的Fragment评论
        setupFragment()



    }


    private fun setupFragment() {
        binding.tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                if (binding.pagerMatchInfo.currentItem != binding.tabs.selectedTabPosition) {
                    binding.pagerMatchInfo.currentItem = binding.tabs.selectedTabPosition
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
            }

        })
        binding.pagerMatchInfo.adapter = MatchInfoPagerAdapter(this)
        binding.pagerMatchInfo.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                if (binding.pagerMatchInfo.currentItem != binding.tabs.selectedTabPosition) {
                    binding.tabs.getTabAt(position)?.select()
                }
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }
        })
    }

    private inner class MatchInfoPagerAdapter(fragment: LivePlayActivity) :
        FragmentStateAdapter(fragment) {

        override fun getItemCount(): Int = homeRunViewModel.totalPage

        override fun createFragment(position: Int): Fragment {
            val fragment = when (position) {
                0 -> LivePlayFragment()
                else -> LiveChartFragment()
            }
            return fragment
        }
    }

    override fun onDestroy() {
        mWsViewModel?.onDestroys()
        mLivePlayer?.stopPlay()
        huiGuLiveViewModel.leaveLive(LiveIdBean().apply {
            liveId = mLiveId
        })
        timer?.cancel()
        timer = null
        super.onDestroy()
    }
}